package st0002;

class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result=new ListNode();
        ListNode m=result;
        int p=l1.val+l2.val;
        int q=p/10;
        result.val=p%10;
        while (l1.next!=null&&l2.next!=null){
            l1=l1.next;
            l2=l2.next;
            p=l1.val+l2.val+q;
            q=p/10;
            m.next=new ListNode(p%10);
            m=m.next;
        }
        while (l1.next!=null){
            l1=l1.next;
            p=l1.val+q;
            q=p/10;
            m.next=new ListNode(p%10);
            m=m.next;
        }
        while (l2.next!=null){
            l2=l2.next;
            p=l2.val+q;
            q=p/10;
            m.next=new ListNode(p%10);
            m=m.next;
        }
        if(q>0){
            m.next=new ListNode(q);
        }
        return result;
    }
    public static void main(String[] args) {
        Solution2 a = new Solution2();
        ListNode temp=new ListNode(3);
        temp=new ListNode(4,temp);
        temp=new ListNode(2,temp);
        ListNode temp2=new ListNode(4);
        temp2=new ListNode(6,temp2);
        temp2=new ListNode(5,temp2);
        a.addTwoNumbers(temp,temp2);
    }
}
